package com.qilu.pe.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ActivityUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.MyApp;
import com.qilu.pe.base.PayResult;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.bean.MyProOrder;
import com.qilu.pe.dao.bean.RefreshEvent;
import com.qilu.pe.dao.bean.UPayInfo;
import com.qilu.pe.dao.bean.WxPayInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.ui.activity.EditOrderActivity;
import com.qilu.pe.ui.activity.PaySuccessActivity;
import com.qilu.pe.ui.activity.ProductOrderDetailsActivity;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 我的商品fragment
public class MyProduct1Fragment extends BaseFragment {
    private RecyclerView rcv_list;// 我的商品列表
    private TextView empty_view;

    private MyProductListAdapter adapter;
    private List<MyProOrder> myProOrderList = new ArrayList<>();

    private String status;

    IWXAPI msgApi;
    private String orderNo;// 下单成功得到的订单号

    public MyProduct1Fragment() {

    }

    public static MyProduct1Fragment newInstance(String status) {
        MyProduct1Fragment fragment = new MyProduct1Fragment();
        Bundle args = new Bundle();
        args.putString("status", status);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new MyProductListAdapter(getActivity());
        status = getArguments().getString("status");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_my_product1, container, false);
        rcv_list = v.findViewById(R.id.rcv_list);
        empty_view = v.findViewById(R.id.empty_view);

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);
        adapter.setDataList(myProOrderList);

        hideProgress();
        reqMyProOrderList();
        showProgress();

        alert = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();
        msgApi = WXAPIFactory.createWXAPI(getActivity(), null);
        msgApi.registerApp(Config.WX_APP_ID);
        EventBus.getDefault().register(this);
        return v;
    }

    private Disposable reqMyProOrderList() {
        return APIRetrofit.getDefault().reqMyProOrderList(Global.HEADER, 1, 999999, status)
                .compose(RxUtil.<BaseResult2<List<MyProOrder>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<MyProOrder>>>() {
                    @Override
                    public void accept(BaseResult2<List<MyProOrder>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            myProOrderList = listBaseResult2.getData();
                            adapter.setDataList(myProOrderList);
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                        if (isDataEmpty(myProOrderList)) {
                            empty_view.setVisibility(View.VISIBLE);
                        } else {
                            empty_view.setVisibility(View.GONE);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        empty_view.setVisibility(View.VISIBLE);
                    }
                });
    }

    private class MyProductListAdapter extends ListBaseAdapter<MyProOrder> {

        public MyProductListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_product_list_mine_fragment;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            CardView cv_item = holder.getView(R.id.cv_item);

            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) cv_item.getLayoutParams();
            if (position == 0) {
                params.topMargin = SizeUtils.dp2px(12);
                params.bottomMargin = SizeUtils.dp2px(6);
            } else if (position == mDataList.size() - 1) {
                params.topMargin = SizeUtils.dp2px(6);
                params.bottomMargin = SizeUtils.dp2px(12);
            } else {
                params.topMargin = SizeUtils.dp2px(6);
                params.bottomMargin = SizeUtils.dp2px(6);
            }

            RoundedImageView iv_pro_pic = holder.getView(R.id.iv_pro_pic);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_status=holder.getView(R.id.tv_status);
            TextView tv_intro = holder.getView(R.id.tv_intro);
            TextView tv_price = holder.getView(R.id.tv_price);
            TextView tv_buy = holder.getView(R.id.tv_buy);
            TextView tv_edit = holder.getView(R.id.tv_edit);

            final MyProOrder order = mDataList.get(position);
            String orderStatus="";
            String status=order.getStatus();
            if(status.equals("0")){
                orderStatus="待付款";
            }else if(status.equals("1")){
                orderStatus="未发货";
            }else if(status.equals("2")){
                orderStatus="已付款";
            }else if(status.equals("3")){
                orderStatus="已发货";
            }else if(status.equals("4")){
                orderStatus="已收货";
            }else if(status.equals("5")){
                orderStatus="退款中";
            }else if(status.equals("6")){
                orderStatus="已取消";
            }
            tv_name.setText(order.getName());
            tv_status.setText(orderStatus);
            tv_intro.setText(order.getIntro());
            tv_price.setText("¥" + order.getPrice());
            GlideUtil.loadImg(Config.URL_IMG + order.getPicture(), iv_pro_pic);

            tv_buy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    orderNo = order.getGood_num();
                    showProgressWithText(true, "");
                    reqUserInfo();
                }
            });

            if ("0".equals(order.getStatus())) {
                tv_buy.setVisibility(View.VISIBLE);
                tv_edit.setVisibility(View.VISIBLE);
            } else {
                tv_buy.setVisibility(View.INVISIBLE);
                tv_edit.setVisibility(View.INVISIBLE);
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getContext(), ProductOrderDetailsActivity.class)
                            .putExtra("orderId", order.getId())
                            .putExtra("order", order));
                }
            });
            tv_edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getContext(), EditOrderActivity.class)
                            .putExtra("orderId", order.getId())
                            .putExtra("order", order));
                }
            });
        }
    }
    private Disposable reqUserInfo() {
        return APIRetrofit.getDefault().getUserInfo(Global.HEADER, "1")
                .compose(RxUtil.<BaseResult2<List<Doctor>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Doctor>>>() {
                    @Override
                    public void accept(BaseResult2<List<Doctor>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<Doctor> doctorList = result2.getData();
                            if (!isDataEmpty(doctorList)) {
                                Doctor doctor = doctorList.get(0);
                                Global.ORG_BALANCE = doctor.getMoney();
                                showDialog();
                            }
                        } else {

                        }
                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }
    private AlertDialog alert;// 弹窗
    private View alert_view;
    String payType = "2";// 支付方式 1 微信,2 支付宝,3 银联支付,4 余额支付

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(getActivity(), R.layout.layout_alert_choose_pay_type, null);

        final RadioButton cb_ali = alert_view.findViewById(R.id.cb_ali);
        final RadioButton cb_wx = alert_view.findViewById(R.id.cb_wx);
        final RadioButton cb_union = alert_view.findViewById(R.id.cb_union);
        final RadioButton cb_balance = alert_view.findViewById(R.id.cb_balance);
        final TextView tv_balance0 = alert_view.findViewById(R.id.tv_balance0);// 显示余额数量

        RelativeLayout rl_ali = alert_view.findViewById(R.id.rl_ali);
        RelativeLayout rl_wechat = alert_view.findViewById(R.id.rl_wechat);
        RelativeLayout rl_union_pay = alert_view.findViewById(R.id.rl_union_pay);
        RelativeLayout rl_balance = alert_view.findViewById(R.id.rl_balance);

        tv_balance0.setText("余额支付 (¥" + Global.ORG_BALANCE + ")");

        rl_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_union_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        cb_union.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        rl_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });
        cb_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_ali.isChecked()) {
                    payType = "2";
                } else if (cb_wx.isChecked()) {
                    payType = "1";
                } else if (cb_union.isChecked()) {
                    payType = "3";
                } else if (cb_balance.isChecked()) {
                    payType = "4";
                }
                if (cb_ali.isChecked()) {// 支付宝
                    hideProgress();
                    reqAliPayInfo();
                    showProgress();
                } else if (cb_wx.isChecked()) {// 微信
                    hideProgress();
                    reqWxPayInfo();
                    showProgress();
                } else if (cb_union.isChecked()) {// 银联
                    hideProgress();
                    reqUPayPayInfo();
                    showProgress();
                } else if (cb_balance.isChecked()) {
                    hideProgress();
                    reqBalancePayInfo();
                    showProgress();
                }
                alert.dismiss();
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, getActivity());
    }

    private Disposable reqBalancePayInfo() {
        if (TextUtils.isEmpty(orderNo)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqshopOrderPayBalance(Global.HEADER, orderNo, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            paySuc();
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_balance = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqUPayPayInfo() {
        if (TextUtils.isEmpty(orderNo)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqshopOrderPayUpay(Global.HEADER, orderNo, payType)
                .compose(RxUtil.<BaseResult2<UPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<UPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            uPay(baseResult2.getData().getTn());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_upay = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqWxPayInfo() {
        if (TextUtils.isEmpty(orderNo)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqshopOrderPayWx(Global.HEADER, orderNo, payType)
                .compose(RxUtil.<BaseResult2<WxPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<WxPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            wxPay(baseResult2);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_wx = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取微信支付信息错误");
                    }
                });
    }

    private Disposable reqAliPayInfo() {
        if (TextUtils.isEmpty(orderNo)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqshopOrderPayAli(Global.HEADER, orderNo, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            String orderInfo = (String) baseResult2.getData();
                            aliPay(orderInfo);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_ali = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 调起银联支付
    private void uPay(String tn) {
//        Logg.i("==银联支付--订单号==" + tn);
        UPPayAssistEx.startPay(getContext(), null, null, tn, MyApp.unionPayMode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String str = data.getExtras().getString("pay_result");
//        Logg.i("==银联支付--回调==" + str);
        if (str.equalsIgnoreCase("success")) {
            paySuc();
        } else if (str.equalsIgnoreCase("fail")) {
            ToastUtils.showShort("银联支付失败");
        } else if (str.equalsIgnoreCase("cancel")) {
            ToastUtils.showShort("您取消了银联支付");
        }
    }

    // 调起微信支付
    private void wxPay(BaseResult2<WxPayInfo> baseResult2) {
        WxPayInfo wxPayInfo = baseResult2.getData();
        PayReq request = new PayReq();
        request.appId = wxPayInfo.getAppid();
        request.partnerId = wxPayInfo.getPartnerid();
        request.prepayId = wxPayInfo.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayInfo.getNoncestr();
        request.timeStamp = wxPayInfo.getTimestamp();
        request.sign = wxPayInfo.getSign();
        msgApi.sendReq(request);
    }

    // 调起支付宝支付
    private void aliPay(final String orderInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 20100851;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @SuppressWarnings("all")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //返回码，标识支付状态，含义如下：9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错
            if (msg.what == 20100851) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String payStatus = payResult.getResultStatus();
                if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                    paySuc();
                } else if (TextUtils.equals(payStatus, "6001")) {
                    ToastUtils.showShort("取消支付");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付失败");
                }
            }
        }
    };

    private void paySuc() {
        Intent intent=new Intent(getActivity(), PaySuccessActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("from", "market");// 标识支付来源
        intent.putExtras(bundle);
        startActivity(intent);
        getActivity().finish();
        EventBus.getDefault().post(new RefreshEvent("refreshProductOrderList"));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCallback(RefreshEvent e) {
        if ("refreshProductOrderList".equals(e.getAction())) {
            reqMyProOrderList();
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}